import pandas as pd

from absl import app, flags

from datetime import datetime, timedelta, time
from xunkemgmt_client.tool.slack_noti import send_to_slack
from xunkemgmt_client.client.util.query_util import query_strategies
from coin.support.pta.logic.mm_report_dumper import MMReportInfoDumper


FLAGS = flags.FLAGS


def generate_daily_market_share_view(market_info):
  market_info['avg_depth'] = (market_info['sell_order_depth'] + market_info['buy_order_depth']) / 2
  market_info = market_info[['market_type', 'exchange', 'symbol',
                             'pta_turnover_in_usd', 'market_turnover_in_usd',
                             'market_share', 'avg_depth', 'uptime_ratio']]
  for col in ('pta_turnover_in_usd', 'market_turnover_in_usd', 'avg_depth'):
    market_info[col] = market_info[col].apply(
        lambda x: '{:,.2f}'.format(x) if pd.notnull(x) else x)
  for col in ('market_share', 'uptime_ratio'):
    market_info[col] = market_info[col].apply(
      lambda x: '{:.2%}'.format(x) if pd.notnull(x) else x)
  rename_dict = {'pta_turnover_in_usd': 'trading_volume($)',
                 'market_turnover_in_usd': 'market_volume($)',
                 'market_share': 'PR(%)',
                 'avg_depth': 'avg_depth_1pct($)',
                 'uptime_ratio': 'uptime(%)'}
  market_info.rename(columns=rename_dict, inplace=True)
  market_info = market_info.dropna()
  return market_info


def main(_):
  strat_df = query_strategies(business_units=['Day1mm', 'ExtDay1mm'])
  strat_list = list(strat_df['strategy_name']) if len(strat_df) > 0 else None
  stats_requirements = pd.read_csv(FLAGS.mm_stat_rqmt_config)
  if FLAGS.trading_date:
    trading_date = datetime.strptime(FLAGS.trading_date, '%Y%m%d')
  else:
    trading_date = datetime.combine(datetime.now() - timedelta(1), time.min)
  coin_list = sorted(list(set(stats_requirements['coin'])))
  mm_report_dumper = MMReportInfoDumper(stats_requirements=stats_requirements,
                                        strat_log_root_dir=FLAGS.strat_log_root_dir,
                                        strat_list=strat_list,
                                        start_date=trading_date,
                                        end_date=trading_date + timedelta(days=1))
  market_info = mm_report_dumper.get_pta_market_info()
  assert len(market_info) > 0, market_info
  working_order_info = mm_report_dumper.get_working_order_info(num_workers=14)
  stat_info = market_info.merge(working_order_info)
  stat_info = generate_daily_market_share_view(stat_info)
  noti_msg = ""
  for coin in coin_list:
    coin_stat_info = stat_info[stat_info['symbol'].str.contains(f'^{coin}')]
    if len(coin_stat_info) > 0:
      coin_stat_info = coin_stat_info.drop(columns='symbol')
      noti_msg += f"{coin} Market Info\nTrading date: {trading_date.date()}\n" + \
        coin_stat_info.to_string(index=False) + "\n\n"
  send_to_slack('```' + noti_msg + '```', FLAGS.slack_receiver, 'msg')


if __name__ == '__main__':
  flags.DEFINE_string('mm_stat_rqmt_config',
                      None,
                      'day1mm strat stat requirement config')
  flags.DEFINE_string('strat_log_root_dir',
                      '/remote/iosg/strat-1/buckets/log.raw.coin/live/strat_slim_proto_log',
                      'strat log root dir')
  flags.DEFINE_string('slack_receiver', None, 'send result to slack')
  flags.DEFINE_string('trading_date', None, '%Y%m%d')
  app.run(main)
